<?php
namespace App\Http\Controllers\Supplier;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Order extends Controller
{
    public function merchantOrder(Request $request)
    {
        try {
            // 获取请求参数
            $userName = $request->input('userName', ''); // 充值账号
            $productType = $request->input('productType', ''); // 商品id
            $recharge_status = $request->input('recharge_status'); // 订单状态
            $start_time = $request->input('start_time', ''); // 开始时间
            $end_time = $request->input('end_time', ''); // 结束时间
            $Merchant_num = $request->input('Merchant_num', ''); // 商户订单号
            $Merchant = $request->input('Merchant', ''); // 商户号
            $mark = $request->input('mark', ''); // 备注
            $goods_code = $request->input('goods_code', ''); // 主商品第三方编码
            $g_code = $request->input('g_code', ''); // 子商品第三方编码
            $types = $request->input('types', 0);
            $sub_id = $request->input('sub_id', 0);
            $per_limit = $request->input('per_limit', 8);
            $page = $request->input('page', 1);

            // 确定查询表
            $table = $types == 1 ? 'xn_invoice_order' : 'xn_batch_order';

            // 构建查询条件
            $condition = $this->buildQueryConditions([
                'userName' => $userName,
                'productType' => $productType,
                'recharge_status' => $recharge_status,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'Merchant_num' => $Merchant_num,
                'Merchant' => $Merchant,
                'mark' => $mark,
                'goods_code' => $goods_code,
                'sub_id' => $sub_id,
                'table' => $table
            ]);

            // 处理g_code特殊查询
            if (!empty($g_code)) {
                return $this->handleGCodeQuery($g_code, $start_time, $end_time);
            }

            // 使用子查询优化分页
            $result = $this->getPaginateWithSubquery($table, $condition, $page, $per_limit);

            // 处理结果数据
            $this->processResultData($result['data'], $table);

            // 返回成功响应
            return successly([
                'list' => $result['data'],
                'total' => $result['total'],
                'page' => $page,
                'pageSize' => $per_limit,
                'totalPage' => $result['totalPage']
            ]);

        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('商户批量订单查询失败: ' . $e->getMessage());
            return fails('查询失败，请稍后重试');
        }
    }

    /**
     * 构建查询条件
     */
    private function buildQueryConditions($params)
    {
        $condition = [];

        // 处理子账户权限
        if (!empty($params['sub_id'])) {
            $sub_goodsId = DB::table('xn_sub_account')
                ->where('id', $params['sub_id'])
                ->select('goods_type', 'power_open')
                ->first();

            if ($sub_goodsId && $sub_goodsId->power_open == 2 && !empty($sub_goodsId->goods_type)) {
                $condition[] = ['goodsId', 'in', explode(',', $sub_goodsId->goods_type)];
            }
        }

        // 时间范围条件
        if (!empty($params['start_time']) && !empty($params['end_time'])) {
            $condition[] = ['recharge_time', '>=', $params['start_time']];
            $condition[] = ['recharge_time', '<=', $params['end_time']];
        }

        // 商户号条件
        if (!empty($params['Merchant'])) {
            $condition[] = ['Merchant_number', '=', $params['Merchant']];
        } else {
            $condition[] = ['Merchant_number', '<>', 0];
        }

        // 其他条件
        $fieldMap = [
            'productType' => 'goodsId',
            'Merchant_num' => 'orderNum',
            'recharge_status' => 'recharge_status',
            'goods_code' => 'goods_code',
            'userName' => 'userName',
            'mark' => 'kmInfo'
        ];

        foreach ($fieldMap as $param => $field) {
            if (!empty($params[$param]) && $params[$param] !== '') {
                $condition[] = [$field, '=', $params[$param]];
            }
        }

        return $condition;
    }

    /**
     * 处理g_code查询
     */
    private function handleGCodeQuery($g_code, $start_time, $end_time)
    {
        $cyc_condition = [];

        if (!empty($start_time) && !empty($end_time)) {
            $cyc_condition[] = ['create_time', '>=', strtotime($start_time)];
            $cyc_condition[] = ['create_time', '<=', strtotime($end_time)];
        }

        $cyc_condition[] = ['g_code', '=', $g_code];

        // 使用子查询优化分页
        $result = $this->getPaginateWithSubquery('each_order', $cyc_condition, 1, 8, 'create_time desc');

        // 获取统计信息
        $counts_info = DB::table('each_order')
            ->where($cyc_condition)
            ->selectRaw('count(IF(state = 1,1,NULL)) as successorder, count(IF(state = 2,1,NULL)) as failsorder')
            ->first();

        return successly([
            'list' => $result['data'],
            'total' => $result['total'],
            'page' => 1,
            'pageSize' => 8,
            'totalPage' => $result['totalPage']
        ],200, $counts_info);
    }

    /**
     * 使用子查询优化分页
     */
    private function getPaginateWithSubquery($table, $condition, $page = 1, $pageSize = 10, $order = 'id DESC')
    {
        // 计算偏移量
        $offset = ($page - 1) * $pageSize;

        // 构建子查询 - 只获取ID
        $subQuery = DB::table($table)
            ->select('id')
            ->where($condition);

        // 处理排序
        $orderParts = explode(' ', $order);
        $subQuery->orderBy($orderParts[0], $orderParts[1] ?? 'asc');

        $subQuery->offset($offset)->limit($pageSize);

        // 获取子查询SQL
        $subSql = $subQuery->toSql();
        $subBindings = $subQuery->getBindings();

        // 主查询 - 通过ID获取完整数据
        $list = DB::table($table . ' as main')
            ->join(DB::raw("($subSql) as sub"), 'main.id', '=', 'sub.id')
            ->mergeBindings($subQuery)
            ->select('main.*')
            ->orderByRaw($order)
            ->get();

        // 获取总记录数
        $total = DB::table($table)
            ->where($condition)
            ->count();

        return [
            'data' => $list,
            'total' => $total,
            'page' => $page,
            'pageSize' => $pageSize,
            'totalPage' => ceil($total / $pageSize)
        ];
    }

    /**
     * 处理结果数据
     */
    private function processResultData(&$data, $table)
    {
        // 如果不是批量订单表，不需要处理额外数据
        if ($table !== 'xn_batch_order') {
            return;
        }

        // 预加载相关数据，减少N+1查询
        $orderNums = $data->pluck('orderNum')->toArray();
        $goodsIds = $data->pluck('goodsId')->toArray();
        $merchantOrderNums = $data->pluck('merchantOrderNum')->toArray();
        $tobShopIds = $data->pluck('tobShopId')->toArray();

        // 批量查询相关数据
        $myyOrders = DB::table('xn_order_myy')
            ->whereIn('orderNum', $orderNums)
            ->get();
        $myyOrdersMap = $myyOrders->keyBy('orderNum');

        $taxedGoods = DB::table('ns_supplier_goods')
            ->whereIn('id', $goodsIds)
            ->pluck('taxed', 'id');

        $couponPrices = DB::table('ns_supplier_goods_coupon')
            ->whereIn('order_sn', $merchantOrderNums)
            ->get();
        $couponPricesMap = $couponPrices->keyBy('order_sn');

        $tobShops = DB::table('xn_TobShop')
            ->whereIn('id', array_filter($tobShopIds))
            ->pluck('shopName', 'id');

        // 处理每条数据
        foreach ($data as $item) {
            // 处理优惠券信息
            if ($item->business == 99 && isset($couponPricesMap[$item->merchantOrderNum])) {
                $couponPrice = $couponPricesMap[$item->merchantOrderNum];
                $item->coupon_price = $couponPrice->price ?? 0.000;
                $item->rechargeMoney = round($item->rechargeMoney - ($couponPrice->price ?? 0), 4);
                $item->carmi = $couponPrice->coupon ?? null;
            }

            // 添加其他关联信息
            $item->myy_order = $myyOrdersMap[$item->orderNum] ?? null;
            $item->taxed = $taxedGoods[$item->goodsId] ?? null;

            // 添加店铺名称
            if ($item->business == 7 && !empty($item->tobShopId)) {
                $item->tob_shopName = $tobShops[$item->tobShopId] ?? null;
            }
        }
    }

}
